package com.example.vueblog.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.vueblog.entity.security.SelfUserDetails;
import com.example.vueblog.entity.User;
import com.example.vueblog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户认证、权限
 * @author yushunshun
 * @date 2022/5/28 22:14
 */
@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //1.通过username查询用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username",username));
        if (user == null) {
            //仍需要细化处理
            throw new UsernameNotFoundException("该用户不存在");
        }

        //TODO 模拟从数据库中获取用户角色
        Set<GrantedAuthority> authoritiesSet = new HashSet<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authoritiesSet.add(authority);
        SelfUserDetails userDetails = new SelfUserDetails();

        //属性拷贝返回UserDetails
        BeanUtils.copyProperties(user, userDetails);
        userDetails.setId(user.getId().intValue());
        userDetails.setAuthorities(authoritiesSet);

        return userDetails;
    }
}
